package v1

import (
	"RoccBlog/global"
	"RoccBlog/model"
	"RoccBlog/model/req_resp"
	"RoccBlog/repository"
	"RoccBlog/util"
)

// TaskProgressRepository 持久层
type TaskProgressRepository struct {
	//实现增删改查接口
	repository.BaseRepository
}

// Create 新增任务进度
func (r *TaskProgressRepository) Create(data model.TaskProgress) error {
	return global.DB.Create(&data).Error
}

// Delete 删除任务进度
func (r *TaskProgressRepository) Delete(id int, userId int) error {
	return global.DB.Where("create_by = ?", userId).Delete(&model.TaskProgress{}, id).Error
}

// Update 更新任务进度
func (r *TaskProgressRepository) Update(data model.TaskProgress, userId int) error {
	return global.DB.Model(&data).Where("create_by = ?", userId).Updates(&data).Error
}

// Select 查询任务进度
func (r *TaskProgressRepository) Select(params req_resp.TaskProgressReq, pageNum, pageSize int, userId int) (any, error) {
	var (
		//数据列表
		list []model.TaskProgress
		//统计
		count int64
		//错误
		err error
	)

	//查询来自 model.TaskProgress
	db := global.DB.Model(&model.TaskProgress{})

	//添加查询条件

	if params.ProjectItemID != nil {
		// ProjectItemID 查询
		db = db.Where("project_item_id = ?", params.ProjectItemID)
	}

	//搜索用户自有数据
	db = db.Where("create_by = ?", userId)

	//查询条数
	err = db.Count(&count).Error
	if err != nil {
		return nil, err
	}

	//分页之后查询列表
	err = db.Order("create_time desc,progress asc").Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&list).Error
	//转换为 util.Page
	return util.ToPageInfo(count, pageSize, pageNum, list), err
}

// SelectById 通过Id查询任务进度
func (r *TaskProgressRepository) SelectById(id int, userId int) (model.TaskProgress, error) {
	var TaskProgress model.TaskProgress
	err := global.DB.Where("create_by = ?", userId).Take(&TaskProgress, id).Error
	return TaskProgress, err
}
